#terry-hardin\miab.py
#
# Copyright (C) 2009 Terry Hardin
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Sheba Praetorius Nobly aWare!



from google.appengine.api import users
from google.appengine.ext import db
from waveapi import events
from waveapi import model
from waveapi import robot
import datetime
import random
import re


RANDOM_MAX = 10

class MessageInABottle(db.Model):
    message = db.StringProperty(required=True)
    sent = db.DateTimeProperty(required=True, auto_now_add=True)
    received = db.DateTimeProperty(required=False)
    rnd = db.IntegerProperty(required=True)
    found = db.BooleanProperty(required=True)

def OnRobotAdded(properties, context):
    #Invoked when the robot has been added.
    root_wavelet = context.GetRootWavelet()
    root_wavelet.CreateBlip().GetDocument().SetText("""~~~~~~~~~~~~\n
    Cast your bottles into the waves!
    To do so, just embed your message in a bottle,
    and then wrap the bottle in two waves

    like so: ~~{message here}~~\n
    
    Who knows where it may turn up, or when :)
    Any bottles cast into the waves can show up in any other wave\n
    In which I am embedded...
    ~~~~~~~~~~~~~~~""")

def OnBlipSubmitted(properties, context):
    #get a handle on the blip
    blip = context.GetBlipById(properties['blipId'])
    #strip out the contents
    contents = blip.GetDocument().GetText()
    #check to see if we have a message to throw in the waves ~~{message}~~
    m = re.search(r'~~\{(.*)\}~~', contents)
    didthrow = 0
    if(m):
        #s = users.get_current_user()
        #we did have a message in a bottle, so create the message
        msg = MessageInABottle(message = m.group(1),
                               rnd = random.randrange(1, RANDOM_MAX),
                               found = False)
        #save the message to the data-store
        msg.put()
        tmpmsg = '~~another message-in-a-bottle disappears into the waves!~~'
        newmsg = re.sub(r'~~\{.*\}~~', tmpmsg, contents, 0)
        blip.GetDocument().SetText(newmsg)
        
        #to-do: we are more likely to get a bottle out of the waves
        didthrow = 1
        #when we throw a bottle into the waves // increase odds somehow
    
    else:
        #not sure if we need to do anything on the else part yet, just a place-holder
        didthrow = 0

    #Now, Check to see if we find a bottle in the waves
    chance = random.randrange(1, RANDOM_MAX)
    query = MessageInABottle.all()
    query.filter('rnd = ', chance)
    query.filter('found = ', False)
    results = query.fetch(1)
    if(results):
        for r in results:
            r.found = True
            r.received = datetime.datetime.now()
            r.put()
            fndmsg = blip.GetDocument().GetText() + "\n~~~~~~~~~~~~\nYOU FOUND A MESSAGE-IN-A-BOTTLE:\n{ " + r.message + " }\n~~~~~~~~~~~~"
            blip.GetDocument().SetText(fndmsg)
            break

if __name__ == '__main__':
    myRobot = robot.Robot('msg-in-a-bottle', 
        image_url='http://msg-in-a-bottle.appspot.com/assets/bottle.png',
        version='1',
        profile_url='http://msg-in-a-bottle.appspot.com/')
    myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
    myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
    myRobot.Run()